package chen.web.message;

import chen.web.InitMyContextFilter;
import chen.web.MyContext;
import chen.web.MyContextProvider;
import chen.web.antispam.JudgeStore;
import chen.web.antispam.CaptchaException;
import chen.web.antispam.CaptchaStore;
import chen.web.antispam.CaptchaStore.VerifyResult;
import chen.web.antispam.Characteristic;
import chen.web.antispam.Judge;
import chen.web.antispam.Regulation;

public class AntiSpamMessageManager extends BaseMessageManagerProxy {

	public static final String Action = "sendMessage";
	
	private CaptchaStore captchaStore;
	public AntiSpamMessageManager(MessageManager mm, JudgeStore anti, CaptchaStore captchaStore) {
		super(mm);
		// TODO Auto-generated constructor stub
		init(anti);
		this.captchaStore = captchaStore;
	}
	
	private Judge judge = null;	
	private void init(JudgeStore anti){
		judge = anti.createJudge(Action, new Regulation(60, 4));
	}

	@Override
	public void send(Message message) {
		// TODO Auto-generated method stub
		Characteristic ch = Characteristic.newInstance();
		if(judge.against(ch)){
			MyContext context = MyContextProvider.getMyContext();
			String uuid = context.getUuid();
			String captcha = (String)context.getAttribute(InitMyContextFilter.Captcha_Attribute_Name);
			VerifyResult result = captchaStore.verify(uuid, captcha);
			if(result != VerifyResult.success){
				throw new CaptchaException(result);		
			}
		}
		super.send(message);
		judge.record(ch);
	}
	
}
